package com.geeksaga.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.geeksaga.common.util.BundleUtils;
import com.geeksaga.domain.SagaFile;
import com.geeksaga.service.FileService;

/**
 * @author newbie
 * @since 0.1
 */
@Controller
public class DownloadController {
    
	protected static final Log logger = LogFactory.getLog(DownloadController.class);
    
    @Autowired private FileService fileService;
    
    @RequestMapping(value = {"/download.do"})
	public void download(@RequestHeader("user-agent") String userAgent, @RequestParam String sid,
			HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        SagaFile file = fileService.findBySid(sid);

        String path = BundleUtils.getString("bbsSaga", "UPLOAD_PATH");
        if(path.equals("default"))
        	path = request.getSession().getServletContext().getRealPath("/upload/" + file.getTargetId());
        else
        	path += "/" + file.getTargetId();
        
        File sourcefile = new File(path + File.separator + file.getFileName());
        logger.info("sourcefile : " + sourcefile.getAbsoluteFile() + " " + sourcefile.exists());

        response.reset();

        if (userAgent.indexOf("MSIE 5.5") != -1) {
            response.setHeader("Content-Type", "doesn/matter;");
            response.setHeader("Content-Disposition", "filename=" + file.getOriginalName() + ";");
        } else if (userAgent.indexOf("MSIE") > -1) {
            response.setHeader("Content-Type", "application/octet-stream;");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getOriginalName(), "UTF-8") + ";");
        } else {
            response.setHeader("Content-Type", "application/octet-stream;");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalName().getBytes("UTF-8"), "latin1") + ";");
            // response.setHeader("Content-Disposition", "inline;filename=" + bbsFile.getOriginalName() + ";");
        }
        
        String mimeType = request.getSession().getServletContext().getMimeType(sourcefile.toString());
        
        if (mimeType == null || mimeType.length() == 0)
            mimeType = "application/octet-stream;";

        response.setContentType(mimeType + "; charset=UTF-8");
        response.setHeader("Content-Length", file.getFileSize());
        response.setHeader("Content-Transfer-Encoding", "binary;");
        response.setHeader("Cache-Control", "private");
        response.setHeader("Pragma", "no-cache;");
        response.setHeader("Expires", "-1;");
        response.setCharacterEncoding("UTF-8");
        
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(sourcefile));
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
                
            byte[] buf = new byte[2048];
            int read = 0;
            while ((read = bufferedInputStream.read(buf)) != -1) 
                bufferedOutputStream.write(buf,0,read);
                
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        } finally {
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                }
            }
        }
    }
}
